package com.ldkj.panzh.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import com.ldkj.panzh.Enum.CameraIdentifierEnum;
import com.ldkj.panzh.param.ArtemisParam;
import com.ldkj.panzh.service.ArtemisPostService;
import com.ldkj.panzh.vo.CameraVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Service
public class ArtemisPostServiceImpl implements ArtemisPostService {

    // API网关相关常量
    private static final String ARTEMIS_PATH = "/artemis";
    private static final String GET_CAMS_API = ARTEMIS_PATH + "/api/video/v2/cameras/previewURLs";

    // RTSP相关常量
    private static final String RTSP_PROTOCOL = "rtsp";
    private static final String RTSP_PREFIX_FORMAT = "rtsp://%s:%s/";
    private static final Pattern RTSP_IP_PATTERN = Pattern.compile("rtsp://([0-9.]+):(\\d+)/");

    // 接口参数常量
    private static final String PROTOCOL_PARAM = "protocol";
    private static final String STREAM_TYPE_PARAM = "streamType";
    private static final String TRANSMODE_PARAM = "transmode";
    private static final String CAMERA_INDEX_CODE_PARAM = "cameraIndexCode";
    private static final String SUCCESS_CODE = "0";

    /**
     * 获取摄像头地址信息
     * @param aParam 接口参数对象
     * @return 摄像头信息列表
     * @throws Exception 处理过程中的异常
     */
    @Override
    public List<CameraVO> getArtemisPostUrl(ArtemisParam aParam) throws Exception {
        // 参数校验
        validateParam(aParam);

        List<String> cameraIps = aParam.getCameraIps();
        Map<String, String> identifiersByIps = CameraIdentifierEnum.getIdentifiersByIps(cameraIps);
        ArtemisConfig config = createArtemisConfig(aParam);

        // 提取host中的IP地址（去除端口部分）
        String targetIp = extractIpFromHost(aParam.getHost());

        // 准备基础参数
        Map<String, String> baseParamMap = new HashMap<>(4);
        baseParamMap.put(PROTOCOL_PARAM, RTSP_PROTOCOL);
        baseParamMap.put(STREAM_TYPE_PARAM, "0");
        baseParamMap.put(TRANSMODE_PARAM, "1");

        Map<String, String> pathMap = Collections.singletonMap("https://", GET_CAMS_API);

        List<CameraVO> resultList = new ArrayList<>(identifiersByIps.size());

        for (Map.Entry<String, String> entry : identifiersByIps.entrySet()) {
            String ip = entry.getKey();
            String identifier = entry.getValue();

            CameraVO cameraVO = processCamera(config, baseParamMap, pathMap, ip, identifier, targetIp);
            resultList.add(cameraVO);
        }

        return resultList;
    }

    /**
     * 处理单个摄像头信息
     */
    private CameraVO processCamera(ArtemisConfig config, Map<String, String> baseParamMap,
                                   Map<String, String> pathMap, String ip, String identifier, String targetIp) {
        CameraVO cameraVO = new CameraVO();
        cameraVO.setIp(ip);
        cameraVO.setCameraIndexCode(identifier);

        try {
            // 复制基础参数并添加当前摄像头标识
            Map<String, String> paramMap = new HashMap<>(baseParamMap);
            paramMap.put(CAMERA_INDEX_CODE_PARAM, identifier);

            String body = JSON.toJSONString(paramMap);
            String response = ArtemisHttpUtil.doPostStringArtemis(
                    config, pathMap, body, null, null, "application/json");

            handleApiResponse(response, cameraVO, targetIp);
        } catch (Exception e) {
            String errorMsg = String.format("解析摄像头[%s]返回结果失败", identifier);
            cameraVO.setErrorMsg(errorMsg);
            log.error(errorMsg, e);
        }

        return cameraVO;
    }

    /**
     * 处理API响应结果
     */
    private void handleApiResponse(String response, CameraVO cameraVO, String targetIp) {
        if (response == null || response.isEmpty()) {
            cameraVO.setErrorMsg("接口返回空响应");
            return;
        }

        try {
            JSONObject jsonObject = JSON.parseObject(response);
            String code = jsonObject.getString("code");

            if (SUCCESS_CODE.equals(code)) {
                JSONObject data = jsonObject.getJSONObject("data");
                if (data != null) {
                    String originalUrl = data.getString("url");
                    cameraVO.setCameraUrl(replaceRtspIp(originalUrl, targetIp));
                } else {
                    cameraVO.setErrorMsg("接口返回数据为空，响应内容: " + response);
                }
            } else {
                String errorMsg = String.format("接口返回错误: %s，响应内容: %s",
                        jsonObject.getString("msg"), response);
                cameraVO.setErrorMsg(errorMsg);
            }
        } catch (Exception e) {
            String errorMsg = String.format("解析响应失败: %s，响应内容: %s",
                    e.getMessage(), response);
            cameraVO.setErrorMsg(errorMsg);
            log.error(errorMsg, e);
        }
    }

    /**
     * 参数校验
     */
    private void validateParam(ArtemisParam param) {
        if (param == null) {
            throw new IllegalArgumentException("参数对象不能为空");
        }
        if (param.getCameraIps() == null || param.getCameraIps().isEmpty()) {
            throw new IllegalArgumentException("摄像头IP列表不能为空");
        }
        if (param.getHost() == null || param.getHost().trim().isEmpty()) {
            throw new IllegalArgumentException("主机地址不能为空");
        }
        if (param.getAppKey() == null || param.getAppKey().trim().isEmpty()) {
            throw new IllegalArgumentException("AppKey不能为空");
        }
        if (param.getAppSecret() == null || param.getAppSecret().trim().isEmpty()) {
            throw new IllegalArgumentException("AppSecret不能为空");
        }
    }

    /**
     * 创建Artemis配置对象
     */
    private ArtemisConfig createArtemisConfig(ArtemisParam param) {
        ArtemisConfig config = new ArtemisConfig();
        config.setAppKey(param.getAppKey());
        config.setAppSecret(param.getAppSecret());
        config.setHost(param.getHost());
        return config;
    }

    /**
     * 从host中提取IP地址（去除端口部分）
     * @param host 格式如 "183.222.26.212:1443"
     * @return 提取的IP地址，如 "183.222.26.212"
     */
    private String extractIpFromHost(String host) {
        if (host == null || host.isEmpty()) {
            throw new IllegalArgumentException("host参数不能为空");
        }
        // 分割host和端口（处理不带端口的情况）
        String[] parts = host.split(":", 2);
        return parts[0];
    }

    /**
     * 替换RTSP URL中的IP地址
     * @param originalUrl 原始RTSP URL
     * @param targetIp 目标IP地址
     * @return 替换后的URL
     */
    private String replaceRtspIp(String originalUrl, String targetIp) {
        if (originalUrl == null || targetIp == null) {
            return originalUrl;
        }

        Matcher matcher = RTSP_IP_PATTERN.matcher(originalUrl);
        if (matcher.find()) {
            String port = matcher.group(2); // 获取原始端口号
            String newPrefix = String.format(RTSP_PREFIX_FORMAT, targetIp, port);
            return matcher.replaceFirst(newPrefix);
        }

        // 若不匹配RTSP格式，返回原始URL并记录警告
        log.warn("URL[{}]不符合RTSP格式，无法替换IP", originalUrl);
        return originalUrl;
    }

}
